<?php
require_once $_SERVER['srcPath'].'/ApplicationTCPConnection.php';
require_once $_SERVER['srcPath'].'/Db.php';

use GrouppaGroup\ApplicationTCPConnection, GrouppaGroup\MCrypt;
use GrouppaGroup\MessageFromApp;
use GrouppaGroup\Db;
use GrouppaGroup\User;
use GrouppaGroup\Controller;
use GrouppaGroup\GeneralServicesController;
/**
 * This class tests almost all functions of the server
 * the tests are run throughout whole system, from translating the message 
 * up to communication with database, all together
 * @author Sylwester Kogowski
 *
 */
class ApplicationTCPConnectionTest extends PHPUnit_Framework_TestCase
{
//the class you want to test is ApplicationTCPConnection.
	/**
	 * @var ApplicationTCPConnection //php will knw what class is gonna be in this variable instance
	 */
	public $instance;
	private $lastUsersIndex;
	private $lastGroupsIndex;
	private $lastCommentId;
	private $lastTopicId;
	private $lastMessageId;
	protected function setUp()
	{
		//We store the autoincrement indices of all tables
		//in order to delete later everything that was created during this session
		$this->instance = new ApplicationTCPConnection();
		$this->lastUsersIndex = TestUtils::getAutoIncrementValue('users');
		$this->lastGroupsIndex = TestUtils::getAutoIncrementValue('groups');
		$this->lastCommentId = TestUtils::getAutoIncrementValue('forum_topics');
		$this->lastTopicId = TestUtils::getAutoIncrementValue('forum_comments');
		$this->lastMessageId = TestUtils::getAutoIncrementValue('chatmessages');
	}
	public function tearDown()
	{
		//delete all created accounts and groups
		Db::getInstance()->sendQuery("DELETE FROM users WHERE id_user >= {$this->lastUsersIndex}");
		Db::getInstance()->sendQuery("DELETE FROM groups WHERE id_group >= {$this->lastGroupsIndex}");
		Db::getInstance()->sendQuery("DELETE FROM forum_topics WHERE id_topic >= {$this->lastTopicId}");
		Db::getInstance()->sendQuery("DELETE FROM forum_comments WHERE id_comment >= {$this->lastCommentId}");
		Db::getInstance()->sendQuery("DELETE FROM chatmessages WHERE id_message >= {$this->lastMessageId}");
	}
	
	public function dataForTest()
	{
		return array(
			array("bolek"),
			array(""),
			array("a"),
			array("casdfasd_Dsa"),
			array('{"fromController":"","id":0,"responseToId":0,"serializedArguments":"blabla","toController":"","toTask":""}'),
			array("ala ma kota"),
			array('{"object1":"mono","object2":12,"object3":[12341,4231]}')
		);
		//will provide arguements, they all have to be arrays inside arrays.
	}
	
	/**
	 * 
	 * @dataProvider dataForTest
	 */
	public function testCompression($text)
	{
		//test dataForTest one after other
		$compressed = $this->instance->compressMessage($text); //compresse and then next line decompresse
		$decompressed = $this->instance->decompressMessage($compressed); 
		//echo = println in java, you dont have to write "" and + sign to add variable, just in the
		//following form.
		echo "\n\nTest compression for text:$text\ncompressed:$compressed\ndecompressed:$decompressed\n";
		$this->assertEquals($text,$decompressed);
		//you have to write $ and ->
	}

	/**
	 *
	 * @dataProvider dataForTest
	 */
	public function testCompressionEncryption($text)
	{
		//test for excryption, compress + encryption + decryption + decompresson.
		//for encryption and decryption.
		$compressedEncrypted = $this->instance->compressEncryptMessages($text);
		$decompressed = $this->instance->decompressDecryptMessages($compressedEncrypted);
		echo "\n\nTest compression and encryption for text:$text\ncompressed+encrypted:$compressedEncrypted\ndecrypted+decompressed:$decompressed\n";
		$this->assertEquals($text,$decompressed);

	}
	
	

	public function userNamePasswordGenerator()
	{
		return array(
				array("test1","mongo123","blabla@dfasdf.net"),
				array("test2","dsfas","airplane@tokyo.flying"),
				array("test3","faeradx3424","maniek@atakuje.vdfv"),
				array('test4','vsdfseewr',"megazord@attack.sad"),
				array('test5','VweDv9q3',"sylwekwazuuup@gmail.com")
		);
	}
	
	
	public function userNamePasswordGenerator2()
	{
		return array(
				array("test5","1234","blabla@dfasdf.net",'monterzy','fwevxcvx'),
				array("test6","4321","airplane@tokyo.flying",'piloci','r3634gxxcb='),
				array("test7","4","maniek@atakuje",'mankuci','fsagcxv'),
				array('test8','5212',"megazord@attack",'idioci','23fvxcv')
		);
	}

	/**
	 * @dataProvider userNamePasswordGenerator2
	 */
	public function testCreateAccount($userName,$password,$email,$groupName,$groupPassword)
	{
		echo "\n\nTesting fully create account\n";
		$message = new MessageFromApp();
		$message->messageType="createAccountResponse";
		$message->serializedArguments = array('email'=>$email,'username'=>$userName,'password'=>$password);
		$message->task='createAccount';
		$message->toController='GeneralServices';
		$message->toGroup='';
		$message->from='';
		$message->id=0;
		$message->accessToken='';
		$json = '['.json_encode($message).']';
		$encrypt = $this->instance->compressEncryptMessages($json);
		$this->instance->loadMessages($encrypt);
		
		TestUtils::assertLastResponseArguments(array('created'=>true));
		
		$this->loginTest($email,$password);
		$this->createGroupTest($groupName,$groupPassword,$userName);
		$this->getUserProfileTest($userName);
		
	}
	
	/**
	 * Tests getting of the user profile 
	 * @param string $userName
	 */
	public function getUserProfileTest( $userName)
	{
		echo "Testing fully getting the profile\n";
		$message = new MessageFromApp();
		$message->messageType="getProfileResponse";
		$message->serializedArguments = array('userName'=>$userName);
		$message->task='getProfile';
		$message->toController='UserAccount';
		$message->toGroup='';
		$message->from=$userName;
		$message->id=0;
		$message->accessToken=GeneralServicesController::getAccessToken($userName);
		$json = '['.json_encode($message).']';
		$encrypt = $this->instance->compressEncryptMessages($json);
		$this->instance->loadMessages($encrypt);
		
		$response = json_decode(TestUtils::getLastResponseParameters());
		$this->assertTrue($response->succeeded);
		$userId = $response->userId;
		$this->changeUserProfileTest($userId, $userName,'5234','some@other.email','anotherUser name',array(
				'telephone'=>'0634252342'
		));
	}
	/**
	 * Tests changing of the user profile 
	 * @param integer $userId
	 * @param string $userName
	 * @param string $pin
	 * @param string $email
	 * @param string $newUserName
	 * @param string $extras
	 */
	public function changeUserProfileTest( $userId, $userName, $pin=null,$email=null,$newUserName=null,$extras=null)
	{
		echo "Testing fully changing the profile\n";
		$message = new MessageFromApp();
		$message->messageType="changeProfileResponse";
		$message->serializedArguments = array(
				'userName'=>$newUserName,
				'pin'=>$pin,
				'email'=>$email,
				'userId'=>$userId
		);
		if($extras && is_array($extras))
			foreach($extras as $key=>$value)
			{
				$message->serializedArguments[$key] = $value;
			}
		$message->task='changeProfile';
		$message->toController='UserAccount';
		$message->toGroup='';
		$message->from=$userName;
		$message->id=0;	
		$message->accessToken=GeneralServicesController::getAccessToken($userName);
		$json = '['.json_encode($message).']';
		$encrypt = $this->instance->compressEncryptMessages($json);
		$this->instance->loadMessages($encrypt);
		
		$response = json_decode(TestUtils::getLastResponseParameters());

		$this->assertTrue($response->succeeded);
		if($extras && is_array($extras))
		{
			$extras2 = $response->extra;
			foreach($extras as $key=>$value)
			{
				$this->assertEquals($extras2->$key, $extras[$key], "Error: $key isn't equal");
			}
		}
		if($pin)
			$this->assertEquals($pin,$response->pin,"Error: pin doesn't match");
		if($email)
			$this->assertEquals($email,$response->email,"Error: email doesn't match");
		if($newUserName)
			$this->assertEquals($newUserName,$response->username,"Error: user name doesn't match");
	}
	public function loginTest($email,$password)
	{
		echo "Testing fully login\n";
		$message = new MessageFromApp();
		$message->messageType="loginResponse";
		$message->serializedArguments = array('email'=>$email,'password'=>$password);
		$message->task='login';
		$message->toController='GeneralServices';
		$message->toGroup='';
		$message->from='';
		$message->id=0;
		$message->accessToken='';
		$json = '['.json_encode($message).']';
		$encrypt = $this->instance->compressEncryptMessages($json);
		$this->instance->loadMessages($encrypt);

		TestUtils::assertLastResponseArguments(array('loggedIn'=>true));
		
		$this->resetPasswordTest($email);
		
	}
	public function resetPasswordTest($email)
	{
		echo "Testing fully reset password\n";
		$message = new MessageFromApp();
		$message->messageType="resetPasswordResponse";
		$message->serializedArguments = array('email'=>$email);
		$message->task='resetPassword';
		$message->toController='GeneralServices';
		$message->toGroup='';
		$message->from='';
		$message->id=0;
		$message->accessToken='';
		$json = '['.json_encode($message).']';
		$encrypt = $this->instance->compressEncryptMessages($json);
		$this->instance->loadMessages($encrypt);
		
		$args = TestUtils::getLastResponseParameters();
		$jsonObj = json_decode($args);
		if(!$jsonObj)
		{// case parameter is just a string, not an object
			//caused by an error, such as wrong email configuration
			echo 'Sending email failed, reason: '.$args."\n";
		}
		else
		{
			$this->assertTrue($jsonObj->emailSent);
		}
	}

	public function createGroupTest($groupName,$groupPassword,$userName)
	{
		echo "Testing fully create Group\n";
		$message = new MessageFromApp();
		$message->messageType="createGroupResponse";
		$message->serializedArguments = array('groupName'=>$groupName,'password'=>$groupPassword,'userName'=>$userName);
		$message->task='createGroup';
		$message->toController='Group';
		$message->toGroup='';
		$message->from=$userName;
		$message->id=0;
		$message->accessToken=GeneralServicesController::getAccessToken($userName);
		$json = '['.json_encode($message).']';
		$encrypt = $this->instance->compressEncryptMessages($json);
		$this->instance->loadMessages($encrypt);
		
		TestUtils::assertLastResponseArguments(array('created'=>true,'joined'=>true));
		
		$this->checkGroupTest($groupName, $userName);
		$this->joinGroupTest($groupName, $userName,$groupPassword);
		$this->chatPostNewMessageGenerator($groupName, $userName);
		$this->getAllMembersTest($groupName, $userName, 1);
		$this->checkAllGroupTest($groupName, $userName);
		$this->changeGroupDataTest($groupName, '5124', $userName);
		$this->leaveGroupTest($groupName, $userName);
		
	}

	public function changeGroupDataTest($groupName,$newGroupPassword,$userName)
	{
		echo "Testing fully changing group data\n";
		$message = new MessageFromApp();
		$message->messageType="changeGroupDataResponse";
		$message->serializedArguments = array('groupName'=>$groupName,'newPin'=>$newGroupPassword);
		$message->task='changeGroupData';
		$message->toController='Group';
		$message->toGroup=$groupName;
		$message->from=$userName;
		$message->id=0;
		$message->accessToken=GeneralServicesController::getAccessToken($userName);
		$json = '['.json_encode($message).']';
		$encrypt = $this->instance->compressEncryptMessages($json);
		$this->instance->loadMessages($encrypt);
	
		TestUtils::assertLastResponseArguments(array('succeeded'=>true));
	}
	public function checkGroupTest($groupName,$userName)
	{
		echo "Testing fully show user group\n";
		$message = new MessageFromApp();
		$message->messageType="userGroupResponse";
		$message->serializedArguments = array('userName'=>$userName);
		$message->task='getUserGroups';
		$message->toController='Group';
		$message->toGroup='';
		$message->from=$userName;
		$message->id=0;
		$message->accessToken=GeneralServicesController::getAccessToken($userName);
		$json = '['.json_encode($message).']';
		$encrypt = $this->instance->compressEncryptMessages($json);
		$this->instance->loadMessages($encrypt);
		$args = TestUtils::getLastResponseParameters(true,'userGroupResponse');
		$jargs = json_decode($args);
		$this->assertTrue(is_array($jargs),'ApplicationTCPConnectionTest.checkGroupTest: response is not an array , response is: '.$args);
		$this->assertTrue(count($jargs)>0,'ApplicationTCPConnectionTest.checkGroupTest: expected at least 1 group, got 0');
		for ($i=0;$i < count($jargs);$i++)
		{
			if($jargs[$i]->groupName== $groupName)
			{
				$this->assertTrue($jargs[$i]->isManager,'the user isn\'t a manager of the group');
				return;
			}
		}
		$this->fail('group wasn\'t joined');
	}
	public function checkAllGroupTest($groupName,$userName)
	{
		echo "Testing fully show all groups\n";
		$message = new MessageFromApp();
		$message->messageType="userGroupResponse";
		$message->serializedArguments = '';
		$message->task='getAllGroups';
		$message->toController='Group';
		$message->toGroup='';
		$message->from=$userName;
		$message->id=0;
		$message->accessToken=GeneralServicesController::getAccessToken($userName);
		$json = '['.json_encode($message).']';
		$encrypt = $this->instance->compressEncryptMessages($json);
		$this->instance->loadMessages($encrypt);
		

		$jargs = json_decode(TestUtils::getLastMessageParams());
		$this->assertTrue(is_array($jargs));
		$this->assertTrue(count($jargs)>0);
		for ($i=0;$i < count($jargs);$i++)
		{
			if($jargs[$i]->groupName== $groupName)
			{
				$this->assertTrue($jargs[$i]->isManager,'the user isn\'t a manager of the group');
				return;
			}
		}
		$this->fail('group wasn\'t joined');
		
		
	}
	public function leaveGroupTest($groupName,$userName)
	{
		echo "Testing fully leave group\n";
		$message = new MessageFromApp();
		$message->messageType="leaveGroupResponse";
		$message->serializedArguments = array('groupName'=>$groupName,'userName'=>$userName);
		$message->task='leaveGroup';
		$message->toController='Group';
		$message->toGroup='';
		$message->from=$userName;
		$message->id=0;
		$message->accessToken=GeneralServicesController::getAccessToken($userName);
		$json = '['.json_encode($message).']';
		$encrypt = $this->instance->compressEncryptMessages($json);
		$this->instance->loadMessages($encrypt);
		
		TestUtils::assertLastResponseArguments(array('left'=>true));
	}
	public function joinGroupTest($groupName,$userName,$password)
	{
		echo "Testing fully join group\n";
		$message = new MessageFromApp();
		$message->messageType="joinGroupResponse";
		$message->serializedArguments = array('groupName'=>$groupName,'password'=>$password,'userName'=>$userName);
		$message->task='joinGroup';
		$message->toController='Group';
		$message->toGroup='';
		$message->from=$userName;
		$message->id=0;
		$message->accessToken=GeneralServicesController::getAccessToken($userName);
		$json = '['.json_encode($message).']';
		$encrypt = $this->instance->compressEncryptMessages($json);
		$this->instance->loadMessages($encrypt);
		TestUtils::assertLastResponseArguments(array('joined'=>true));
		$this->joinGroupTestWrongPassword($groupName, $userName);
		$this->joinGroupTestWrongPasswordUserName($userName);
		
		$nTopics = $this->getTopicsTest($userName, $groupName);
		$this->addTopicTest($userName, $groupName);
		$this->assertEquals($nTopics+1, $this->getTopicsTest($userName, $groupName));
		
	}
	public function joinGroupTestWrongPassword($groupName,$userName)
	{
		$password='fcvrtfgdfgserts';
		echo "Testing fully join group with wrong password\n";
		$message = new MessageFromApp();
		$message->messageType="joinGroupResponse";
		$message->serializedArguments = array('groupName'=>$groupName,'password'=>$password,'userName'=>$userName);
		$message->task='joinGroup';
		$message->toController='Group';
		$message->toGroup='';
		$message->from=$userName;
		$message->id=0;
		$message->accessToken=GeneralServicesController::getAccessToken($userName);
		$json = '['.json_encode($message).']';
		$encrypt = $this->instance->compressEncryptMessages($json);
		$this->instance->loadMessages($encrypt);
		TestUtils::assertLastResponseArguments(array('joined'=>false));
	}
	public function joinGroupTestWrongPasswordUserName($userName)
	{
		$groupName='fdvxerwcvxc';
		$password='fcvrtfgdfgserts';
		echo "Testing fully join group with wrong password and group name\n";
		$message = new MessageFromApp();
		$message->messageType="joinGroupResponse";
		$message->serializedArguments = array('groupName'=>$groupName,'password'=>$password,'userName'=>$userName);
		$message->task='joinGroup';
		$message->toController='Group';
		$message->toGroup='';
		$message->from=$userName;
		$message->id=0;
		$message->accessToken=GeneralServicesController::getAccessToken($userName);
		$json = '['.json_encode($message).']';
		$encrypt = $this->instance->compressEncryptMessages($json);
		$this->instance->loadMessages($encrypt);
		TestUtils::assertLastResponseArguments(array('joined'=>false));
	}
	
	public function getAllMembersTest($groupName, $userName, $expectedNumber)
	{
		$message = new MessageFromApp();
		$message->messageType="getAllGroupMembersResponse";
		$message->serializedArguments = array('groupName'=>$groupName);
		$message->task='getAllMembers';
		$message->toController='Group';
		$message->toGroup = $groupName;
		$message->from=$userName;
		$message->id=0;
		$message->accessToken=GeneralServicesController::getAccessToken($userName);
		$json = '['.json_encode($message).']';
		$encrypt = $this->instance->compressEncryptMessages($json);
		$this->instance->loadMessages($encrypt);
		$response = json_decode(TestUtils::getLastMessageParams());
		$n = count($response);
		$this -> assertEquals($expectedNumber, $n);
	}
	

	public function addTopicTest($userName,$groupName)
	{
		echo "Testing fully adding a topic\n";
		$message = new MessageFromApp();
		$message->messageType="addTopicResponse";
		$message->serializedArguments = array(
				'topicTitle'=>'test title',
				'topicIsPinned'=>false,
				'groupName'=>$groupName,
				'topicText'=>'ala ma kota tralalalalala'
		);
		$message->task='addTopic';
		$message->toController='Forum';
		$message->toGroup=$groupName;
		$message->from=$userName;
		$message->id=0;
		$message->accessToken=GeneralServicesController::getAccessToken($userName);
		$json = '['.json_encode($message).']';
		$encrypt = $this->instance->compressEncryptMessages($json);
		$this->instance->loadMessages($encrypt);
		$response = TestUtils::getLastResponseParameters();
		$argsObject = json_decode($response);
		if(!$argsObject)
		{
			throw new \Exception('Expected object, got something else: '.$response);
		}
		$this->assertTrue($argsObject->succeeded);

		$topicId = $argsObject->topic->topicId;
		$this->assertEquals(0,$this->getAllCommentsTest($userName, $groupName, $topicId));
		$commentId = $this->addCommentTest($userName, $groupName, $topicId);
		$this->assertEquals(1,$this->getAllCommentsTest($userName, $groupName, $topicId));
		$this->assertEquals(1,$this->getNewCommentsTest($userName, $groupName, $topicId, -1));
		$this->assertEquals(0,$this->getNewCommentsTest($userName, $groupName, $topicId, $commentId));
		$this->assertEquals(1,$this->getNewCommentsTest($userName, $groupName, $topicId, $commentId-1));
		$this->changeTopicTest($userName, $groupName, $topicId);
	}
	public function changeTopicTest($userName,$groupName,$topicId)
	{
		echo "Testing fully changing a topic\n";
		$message = new MessageFromApp();
		$message->messageType="changeTopicResponse";
		$message->serializedArguments = array(
				'topicTitle'=>'other title',
				'topicIsPinned'=>true,
				'topicText'=>'ala ma kota tralalalalala',
				'topicId'=>$topicId
		);
		$message->task='changeTopic';
		$message->toController='Forum';
		$message->toGroup=$groupName;
		$message->from=$userName;
		$message->id=0;
		$message->accessToken=GeneralServicesController::getAccessToken($userName);
		$json = '['.json_encode($message).']';
		$encrypt = $this->instance->compressEncryptMessages($json);
		$this->instance->loadMessages($encrypt);
		$response = TestUtils::assertLastResponseArguments(array('succeeded'=>true));
	}
	/**
	 * Will return number of topics for this group
	 * @param string $userName 
	 * @param string $groupName 
	 * @throws \Exception
	 * @return integer number of topics read
	 */
	public function getTopicsTest($userName,$groupName)
	{
		echo "Testing fully getting all topics\n";
		$message = new MessageFromApp();
		$message->messageType="getAllTopicsResponse";
		$message->serializedArguments = array(
				'groupName'=>$groupName
		);
		$message->task='getAllTopics';
		$message->toController='Forum';
		$message->toGroup=$groupName;
		$message->from=$userName;
		$message->id=0;
		$message->accessToken=GeneralServicesController::getAccessToken($userName);
		$json = '['.json_encode($message).']';
		$encrypt = $this->instance->compressEncryptMessages($json);
		$this->instance->loadMessages($encrypt);
		$response = TestUtils::getLastResponseParameters(false,'getAllTopicsResponse');
		if($response == null)
			return 0;
		$argsObject = json_decode($response);
		if(!$argsObject)
		{
			throw new \Exception('Expected object, got something else: '.$response);
		}
		
		$this->assertTrue($argsObject->succeeded);
		$maxVersion = $argsObject->maxVersion;
		$this->assertEquals(0,$this->getNewTopicsTest($userName, $groupName, $maxVersion));
		$this->assertEquals(1,$this->getNewTopicsTest($userName, $groupName, $maxVersion-1));
		return count($argsObject->topics);
		
	}
	/**
	 * Will return number of new topics for this group
	 * @param string $userName 
	 * @param string $groupName 
	 * @param integer $sinceVersion 
	 * @throws \Exception
	 * @return integer number of topics read
	 */
	public function getNewTopicsTest($userName,$groupName,$sinceVersion)
	{
		echo "Testing fully getting all new topics\n";
		$message = new MessageFromApp();
		$message->messageType="getNewTopicsResponse";
		$message->serializedArguments = array(
				'groupName'=>$groupName,
				'sinceVersion'=>$sinceVersion
		);
		$message->task='getAllTopics';
		$message->toController='Forum';
		$message->toGroup=$groupName;
		$message->from=$userName;
		$message->id=0;
		$message->accessToken=GeneralServicesController::getAccessToken($userName);
		$json = '['.json_encode($message).']';
		$encrypt = $this->instance->compressEncryptMessages($json);
		$this->instance->loadMessages($encrypt);
		$response = TestUtils::getLastResponseParameters(false,'getNewTopicsResponse');
		if($response == null)
			return 0;
		$argsObject = json_decode($response);
		if(!$argsObject)
		{
			throw new \Exception('Expected object, got something else: '.$response);
		}
		
		$this->assertTrue($argsObject->succeeded);
		return count($argsObject->topics);
		
	}
	public function addCommentTest($userName,$groupName,$topicId)
	{
		echo "Testing fully adding a comment\n";
		$message = new MessageFromApp();
		$message->messageType="addCommentResponse";
		$message->serializedArguments = array(
				'commentTopicId'=>$topicId,
				'groupName'=>$groupName,
				'commentText'=>'ala ma kota tralalalalala'
		);
		$message->task='addComment';
		$message->toController='Forum';
		$message->toGroup=$groupName;
		$message->from=$userName;
		$message->id=0;
		$message->accessToken=GeneralServicesController::getAccessToken($userName);
		$json = '['.json_encode($message).']';
		$encrypt = $this->instance->compressEncryptMessages($json);
		$this->instance->loadMessages($encrypt);
		$response = json_decode(TestUtils::getLastResponseParameters());
		$this->assertTrue($response->succeeded);
		return $response->comment->commentId;
	}

	/**
	 * Will return number of new comments for specified topic
	 * @param string $userName
	 * @param string $groupName
	 * @param integer $topicID
	 * @param integer $sinceID id from which load comments (exclusive)
	 * @throws \Exception
	 * @return integer number of comments read
	 */
	public function getNewCommentsTest($userName,$groupName,$topicID,$sinceID)
	{
		echo "Testing fully getting all new comments\n";
		$message = new MessageFromApp();
		$message->messageType="getNewCommentsResponse";
		$message->serializedArguments = array(
				'topicId'=>$topicID,
				'sinceID'=>$sinceID
		);
		$message->task='getAllComments';
		$message->toController='Forum';
		$message->toGroup=$groupName;
		$message->from=$userName;
		$message->id=0;
		$message->accessToken=GeneralServicesController::getAccessToken($userName);
		$json = '['.json_encode($message).']';
		$encrypt = $this->instance->compressEncryptMessages($json);
		$this->instance->loadMessages($encrypt);
		$response = TestUtils::getLastResponseParameters(false,'getNewCommentsResponse');
		if($response == null)
			return 0;
		$argsObject = json_decode($response);
		if(!$argsObject)
		{
			throw new \Exception('Expected object, got something else: '.$response);
		}
	
		$this->assertTrue($argsObject->succeeded);
		return count($argsObject->comments);
	
	}
	/**
	 * Will return number of comments for specified topic
	 * @param string $userName
	 * @param string $groupName
	 * @param integer $topicID
	 * @throws \Exception
	 * @return integer number of comments read
	 */
	public function getAllCommentsTest($userName,$groupName,$topicID)
	{
		echo "Testing fully getting all new comments\n";
		$message = new MessageFromApp();
		$message->messageType="getNewCommentsResponse";
		$message->serializedArguments = array(
				'topicId'=>$topicID,
		);
		$message->task='getAllComments';
		$message->toController='Forum';
		$message->toGroup=$groupName;
		$message->from=$userName;
		$message->id=0;
		$message->accessToken=GeneralServicesController::getAccessToken($userName);
		$json = '['.json_encode($message).']';
		$encrypt = $this->instance->compressEncryptMessages($json);
		$this->instance->loadMessages($encrypt);
		$response = TestUtils::getLastResponseParameters(false,'getNewCommentsResponse');
		if($response == null)
			return 0;
		$argsObject = json_decode($response);
		if(!$argsObject)
		{
			throw new \Exception('Expected object, got something else: '.$response);
		}
	
		$this->assertTrue($argsObject->succeeded);
		return count($argsObject->comments);
	
	}
	public function chatPostNewMessageGenerator($groupName,$author)
	{
		$curId = TestUtils::getAutoIncrementValue('chatmessages');
		$amt = $this->chatGetMessagesTest($groupName,$author,0);
		$this->chatPostNewMessageTest($groupName,$author,'ala ma kota');
		$this->chatGetMessagesTest($groupName,$author,$amt+1);
		$this->chatGetNewMessagesTest($groupName,$author,$amt+1,$curId);
		$this->chatGetNewMessagesTest($groupName,$author,$amt+0,TestUtils::getAutoIncrementValue('chatmessages'));
		$this->chatPostNewMessageTest($groupName,$author,'Michaeeel do some programming!');
		$this->chatGetMessagesTest($groupName,$author,$amt+2);
		$this->chatGetNewMessagesTest($groupName,$author,$amt+2,$curId);
		$this->chatGetNewMessagesTest($groupName,$author,$amt+0,TestUtils::getAutoIncrementValue('chatmessages'));
		$this->chatPostNewMessageTest($groupName,$author,'Henryyyyyyyy make test caseseeseseses!');
		$this->chatGetMessagesTest($groupName,$author,$amt+3);
		$this->chatGetNewMessagesTest($groupName,$author,$amt+3,$curId);
		$this->chatGetNewMessagesTest($groupName,$author,$amt+0,TestUtils::getAutoIncrementValue('chatmessages'));
		$this->chatPostNewMessageTest($groupName,$author,'Nooooooooooooooooo');
		$this->chatGetMessagesTest($groupName,$author,$amt+4);
		$this->chatGetNewMessagesTest($groupName,$author,$amt+4,$curId);
		$this->chatGetNewMessagesTest($groupName,$author,$amt+0,TestUtils::getAutoIncrementValue('chatmessages'));
	}
	
	public function chatPostNewMessageTest($groupName,$author,$text)
	{
		echo "Testing fully posting a message to chat\n";
		$date = strtotime('now');
		$message = new MessageFromApp();
		$message->messageType="postNewMessageResponse";
		$message->serializedArguments = array(
				'author'=>$author,
				'groupName'=>$groupName,
				'text'=>$text,
				'date'=>$date,
				'idFrom'=>0
		);
		$message->task='postNewMessage';
		$message->toController='Chat';
		$message->toGroup=$groupName;
		$message->from=$author;
		$message->id=0;
		$message->accessToken=GeneralServicesController::getAccessToken($author);
		$json = '['.json_encode($message).']';
		$encrypt = $this->instance->compressEncryptMessages($json);
		$this->instance->loadMessages($encrypt);
		TestUtils::assertLastResponseArguments(array('posted'=>true));
		
	}
	public function chatGetMessagesTest($groupName,$userName,$expectedAmount)
	{
		echo "Testing fully getting all messages\n";
		$date = strtotime('now');
		$message = new MessageFromApp();
		$message->messageType="getMessageResponse";
		$message->serializedArguments = array(
				'userName'=>$userName,
				'groupName'=>$groupName
		);
		$message->task='getMessages';
		$message->toController='Chat';
		$message->toGroup=$groupName;
		$message->from=$userName;
		$message->id=0;
		$message->accessToken=GeneralServicesController::getAccessToken($userName);
		$json = '['.json_encode($message).']';
		$encrypt = $this->instance->compressEncryptMessages($json);
		$this->instance->loadMessages($encrypt);
		$response = json_decode(TestUtils::getLastResponseParameters());
		$messageAmount = count($response->all_messages);
		$this->assertGreaterThanOrEqual($expectedAmount,$messageAmount);
		return $messageAmount;
	}
	public function chatGetNewMessagesTest($groupName,$userName,$expectedAmount,$fromId)
	{
		echo "Testing fully getting all new messages\n";
		$date = strtotime('now');
		$message = new MessageFromApp();
		$message->messageType="getMessageResponse";
		$message->serializedArguments = array(
				'userName'=>$userName,
				'groupName'=>$groupName,
				'idFrom'=>$fromId
		);
		$message->task='getMessages';
		$message->toController='Chat';
		$message->toGroup=$groupName;
		$message->from=$userName;
		$message->id=0;
		$message->accessToken=GeneralServicesController::getAccessToken($userName);
		$json = '['.json_encode($message).']';
		$encrypt = $this->instance->compressEncryptMessages($json);
		$this->instance->loadMessages($encrypt);
		$response = json_decode(TestUtils::getLastResponseParameters());
		$this->assertGreaterThanOrEqual($expectedAmount,count($response->all_messages));
	}
}